package adv.i31.bluetoothtest;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAssignedNumbers;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHealth;
import android.bluetooth.BluetoothHealthAppConfiguration;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	public static final String				TAG	= "Bluetoothtest";
	// private static final UUID MY_UUID =
	// UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

	private BluetoothAdapter				mAdapter;

	private ArrayAdapter<BluetoothDevice>	mDevicesAdapter;
	private ArrayList<BluetoothDevice>		mDevices;

	private ListView						mListView;
	private Button							mScanButton;

	private BroadcastReceiver				mReceiverFound;
	private BroadcastReceiver				mReceiverDiscoveryStarted;
	private BroadcastReceiver				mReceiverDiscoveryFinished;

	private Button							mStartServerButton;

	private void quickToast(String s)
	{
		Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(mReceiverFound);
		unregisterReceiver(mReceiverDiscoveryFinished);
		unregisterReceiver(mReceiverDiscoveryStarted);
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// make sure the device supports Bluetooth
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mAdapter == null) {
			throw new RuntimeException("Device does not support Bluetooth");
		}

		// make sure the Bluetooth adapter is active
		if (!mAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivity(enableBtIntent);
		}

		// get access to the ui views
		mListView = (ListView) findViewById(R.id.listView1);
		mScanButton = (Button) findViewById(R.id.button1);
		mStartServerButton = (Button) findViewById(R.id.button2);

		mStartServerButton.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				BluetoothServerSocket serverSocket = null;
				BluetoothSocket socket = null;
				try {
					quickToast("Creating BluetoothServerSocket");
					serverSocket = mAdapter.listenUsingRfcommWithServiceRecord(TAG,
							UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"));
					
					//serverSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(TAG,
					//		UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"));
					

					quickToast("awaiting connections");
					socket = serverSocket.accept();
					quickToast("Accepted a connection");

				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (serverSocket != null)
							serverSocket.close();
						if (socket != null)
							socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					quickToast("Server ended");
				}
			}
		});

		// The receiver that will be called when a device is found
		mReceiverFound = new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context context, Intent intent)
			{

				String action = intent.getAction();
				quickToast("mReceiverFound received:\n" + intent.getAction());

				if (BluetoothDevice.ACTION_FOUND.equals(action)) {
					// get the discovered remote BT device
					BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

					if (!mDevices.contains(device)) {
						mDevices.add(device);
						// notify the adapter that the ListView needs to be
						// redrawn because an item was added
						mDevicesAdapter.notifyDataSetChanged();
					} else {
						quickToast("Device: " + device.getName() + " already listed");
					}
					// Stop the search after 1 device was found
					mAdapter.cancelDiscovery();
				}
			}
		};

		// The receiver that will be called when a search for BT devices has
		// started
		mReceiverDiscoveryStarted = new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context context, Intent intent)
			{
				quickToast("mReceiverDiscoveryStarted received:\n" + intent.getAction());
				if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(intent.getAction())) {

					mScanButton.setText("Scanning... (cancel scan)");
				}
			}
		};

		// The receiver that will be called when a search for BT devices has
		// ended
		mReceiverDiscoveryFinished = new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context context, Intent intent)
			{
				quickToast("mReceiverDiscoveryFinished received:\n" + intent.getAction());
				if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())) {
					mScanButton.setText("Start Scan");
				}
			}
		};

		// initalize BroadcastReceivers to handle BT device search
		IntentFilter filterActionFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		IntentFilter filterDiscoveryStarted = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		IntentFilter filterDiscoveryFinished = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(mReceiverFound, filterActionFound);
		registerReceiver(mReceiverDiscoveryStarted, filterDiscoveryStarted);
		registerReceiver(mReceiverDiscoveryFinished, filterDiscoveryFinished);

		// All the discovered BT devices will go here
		mDevices = new ArrayList<BluetoothDevice>();
		// Add all bonded devices to the list
		mDevices.addAll(mAdapter.getBondedDevices());

		// the Adapter will handle the population of the ListView with items
		// from the ArrayList
		mDevicesAdapter = new ArrayAdapter<BluetoothDevice>(this, R.layout.listitem, R.id.textView1, mDevices);
		mListView.setAdapter(mDevicesAdapter);

		mScanButton.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				Log.i(TAG, "onClick");

				if (mAdapter.isDiscovering()) {
					mAdapter.cancelDiscovery();
				} else {
					// Start scanning for BT devices
					mAdapter.startDiscovery();
				}
			}
		});

		mListView.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				BluetoothDevice device = mDevices.get(position);
				quickToast("connecting to MAC:  " + device.getAddress() + "\nName: " + device.getName());

				BluetoothHealth bh;
				BluetoothHealthAppConfiguration appc;

				BluetoothSocket socket = null;
				try {
					Log.i(TAG, "creating socket");
					socket = device.createRfcommSocketToServiceRecord(UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"));
		
					Log.i(TAG, "connecting");
					socket.connect();
					OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
					Log.i(TAG, "writing");
					writer.append('a');

				} catch (IOException e) {
					e.printStackTrace();

				} finally {
					Log.i(TAG, "finally");
					try {
						socket.close();
					} catch (IOException e) {
					}
				}

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
}
